package com.cloudbroker.bcs.platform.dav.middle.bizservice.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.cloudbroker.bcs.platform.dav.middle.entity.*;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.util.JSONUtil;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.back.SelfViewpointBack;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.back.SelfViewpointList;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.back.SelfViewpointResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.vo.SelfViewpointByIdForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.vo.SelfViewpointForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.vo.SelfViewpointReviewForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.vo.SelfViewpointStatusForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.vo.ViewPointReviewForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.vo.ViewpointReviewManage;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.system.vo.ViewpointReviewManageForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.ViewpointManageBizService;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.vo.BranchNoPageForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.ViewpointCommentOperateList;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.ViewpointCommentOperateListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.ViewpointDetailDavList;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.ViewpointManageList;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.ViewpointManangeResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.ViewpointOperateList;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.ViewpointOperateListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.result.ViewpointReviewData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.ViewpointCommentOperateDeleteForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.ViewpointCommentOperateListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.ViewpointDetailListForm;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.middle.entityexample.ViewpointReplyId;
import com.cloudbroker.bcs.platform.dav.middle.entityview.ViewpointCommentOperateListView;
import com.cloudbroker.bcs.platform.dav.middle.entityview.ViewpointDetailDavView;
import com.cloudbroker.bcs.platform.dav.middle.entityview.ViewpointReviewView;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerManagerService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerService;
import com.cloudbroker.bcs.platform.dav.middle.service.TenantService;
import com.cloudbroker.bcs.platform.dav.middle.service.ViewpointMsgService;
import com.cloudbroker.bcs.platform.dav.middle.service.ViewpointReplyService;
import com.cloudbroker.bcs.platform.dav.middle.util.SearchUtil;
import com.cloudbroker.bcs.platform.dav.middle.util.ViewpointMsgFormatUtil;

/**
 * Created by lnq on 2016/12/29.
 */
@Service
public class ViewpointManageBizServiceImpl implements ViewpointManageBizService {
    @Resource
    private TenantService tenantService;
    @Resource
    private ViewpointMsgService viewpointMsgService;
    @Resource
    private BrokerService brokerService;
    @Resource
    private ViewpointReplyService viewpointReplyService;
    @Resource
    private BrokerManagerService brokerManagerService;

    @Override
    public HSBCPSBackVO funcViewpointReviewManage(ViewPointReviewForm form) {
        String viewpoint_check_flag = form.getViewpoint_check_flag();
        List<Long> tenantIds =  tenantService.getTenantIdsByBranchNo(form.getBranch_no());
        tenantService.updateStatusByTenantId(viewpoint_check_flag,tenantIds);
        HSBCPSBackVO result = new HSBCPSBackVO();
        return VOUtil.setSuccessResult(result);
    }

    @Override
    public ViewpointReviewData funcViewpointReviewStatusManange(ViewpointReviewManage form) {
        String branchNo = form.getBranch_no();
        Tenant tenant = tenantService.getByBranchNo(branchNo);
        if(tenant == null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.OperateErr.TENANT_NOT_EXIST_BY_BRANCH, ViewpointReviewData.class);
        }
        ViewpointReviewData viewpointReviewData = new ViewpointReviewData();
        viewpointReviewData.setViewpoint_check_flag(ValueUtil.getInt(tenant.getViewpoint_check_flag(),0));
        return VOUtil.setSuccessResult(viewpointReviewData);
    }

    @Override
    public ViewpointManangeResult funcViewpointListManage(SelfViewpointForm form) {
        String key_word = form.getKey_word();
        Integer page_no = ValueUtil.getInt(form.getPage_no(), 1);
        Integer page_count = ValueUtil.getInt(form.getPage_count(), ConfigValues.getRequestNum());
        List<Long> tenantIds =  tenantService.getTenantIdsByBranchNo(form.getBranch_no());
        if(tenantIds == null || tenantIds.size()<=0){
            return  VOUtil.genErrorResult(HSBCPSErrorCodes.OperateErr.TENANT_NOT_EXIST_BY_BRANCH, ViewpointManangeResult.class);
        }
        Integer total = viewpointMsgService.countNoLogin(key_word,tenantIds);
        List<ViewpointReviewView> viewpointReviewViews = viewpointMsgService.funcViewpointReviewManange(key_word,(page_no - 1) * page_count,page_count,tenantIds);
        List<ViewpointManageList> viewpointManageLists = new ArrayList<>();
        if(viewpointReviewViews != null && viewpointReviewViews.size() > 0){
            for(ViewpointReviewView list : viewpointReviewViews){
                ViewpointManageList viewpointManageList = new ViewpointManageList();
                viewpointManageList.setBroker_name(list.getBroker_name());
                viewpointManageList.setSend_time(list.getSend_time());
                viewpointManageList.setViewpoint_id(list.getViewpoint_id());
                viewpointManageList.setViewpoint_abstract(list.getViewpoint_abstract());
                viewpointManageList.setViewpoint_content(ViewpointMsgFormatUtil.parseContext(list.getViewpoint_content()));
                viewpointManageList.setViewpoint_public_status(list.getViewpoint_public_status());
                viewpointManageLists.add(viewpointManageList);
            }
        }
        ViewpointManangeResult result = new ViewpointManangeResult();
        result.setTotal_item_num(total);
        result.setPage_no(page_no);
        result.setPage_size(page_count);
        result.setData_list(viewpointManageLists);
        return VOUtil.setSuccessResult(result);
    }

    @Override
    public HSBCPSBackVO funcViewpointReviewByIdManage(ViewpointReviewManageForm form) {
        String viewpoint_id = form.getViewpoint_id();
        String viewpoint_public_status = form.getViewpoint_public_status();
        viewpointMsgService.funcViewpointReviewByIdManage(viewpoint_id,viewpoint_public_status);
        HSBCPSBackVO result = new HSBCPSBackVO();
        return VOUtil.setSuccessResult(result);
    }

    @Override
    public ViewpointOperateList funcViewpointOperateListByTenant(BranchNoPageForm form) {
        List<Long> tenant_ids = tenantService.getTenantIdsByBranchNo(form.getBranch_no());
        Integer pageNo = ValueUtil.getInt(form.getPage_no(), 1);
        Integer pageSize = ValueUtil.getInt(form.getPage_count(), ConfigValues.getRequestNum());
        ViewpointOperateList result = new ViewpointOperateList();
        List<ViewpointOperateListData> resultList = new ArrayList<>();
        Integer counts = 0;
        if (tenant_ids != null && !tenant_ids.isEmpty()) {
            counts = viewpointMsgService.countByTenant(tenant_ids);
            List<ViewpointMsg> viewpointMsgs = viewpointMsgService.qryListByTenant(tenant_ids, (pageNo - 1) * pageSize, pageSize);
            for (ViewpointMsg viewpointMsg: viewpointMsgs) {
                Broker broker = brokerService.getById(viewpointMsg.getBroker_id(), viewpointMsg.getTenant_id());
                    ViewpointOperateListData viewpointOperateListData = new ViewpointOperateListData();
                    JSONObject viewpointTitle = JSON.parseObject(viewpointMsg.getViewpoint_content());
                    if (!StringUtil.isBlank(viewpointTitle.getString("title"))) {
                        viewpointOperateListData.setViewpoint_title(viewpointTitle.getString("title"));
                    } else {
                        int last = Math.min(viewpointMsg.getViewpoint_abstract().length(), 200);
                        viewpointOperateListData.setViewpoint_title(viewpointMsg.getViewpoint_abstract().substring(0, last));
                    }
                    if (broker != null) {
                        viewpointOperateListData.setBroker_name(broker.getBroker_name());
                    }
                    viewpointOperateListData.setViewpoint_id(viewpointMsg.getViewpoint_id());
                    viewpointOperateListData.setTenant_id(viewpointMsg.getTenant_id());
                    resultList.add(viewpointOperateListData);
            }
        }
        result.setTotal_item_num(counts);
        result.setPage_no(pageNo);
        result.newDataList().addAll(resultList);
        return VOUtil.setSuccessResult(result);
    }

    @Override
    public ViewpointCommentOperateList funcViewpointCommentOperateListByTenant(ViewpointCommentOperateListForm form) {
        Long viewpointId = ValueUtil.getLong(form.getViewpoint_id());
        Integer tenantId = ValueUtil.getInt(form.getTenant_id());
        List<Long> tenant_ids = tenantService.getTenantIdsByBranchNo(form.getBranch_no());
        if (!tenant_ids.contains(ValueUtil.getLong(tenantId))) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.TENAN_ID_ERROR, ViewpointCommentOperateList.class);
        }
        ViewpointMsg viewpointMsg = viewpointMsgService.getByTenantId(viewpointId, tenantId);
        if (viewpointMsg == null) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_VIEWPOINT_ID, ViewpointCommentOperateList.class);
        }
        String keyword = form.getKeyword();
        Integer pageNo = ValueUtil.getInt(form.getPage_no(), 1);
        Integer pageSize = ValueUtil.getInt(form.getPage_count(), ConfigValues.getRequestNum());
        Integer counts = viewpointReplyService.countByViewpoint(viewpointId, keyword, tenantId);
        List<ViewpointCommentOperateListView> viewpointReplies = viewpointReplyService.getByViewpoint(viewpointId, keyword, tenantId,(pageNo - 1) * pageSize, pageSize);
        ViewpointCommentOperateList result = new ViewpointCommentOperateList();
        List<ViewpointCommentOperateListData> resultList = new ArrayList<>();
        for (ViewpointCommentOperateListView viewpointCommentOperateListView : viewpointReplies) {
            ViewpointCommentOperateListData viewpointCommentOperateListData = new ViewpointCommentOperateListData();
            viewpointCommentOperateListData.setReply_id(viewpointCommentOperateListView.getReply_id());
            viewpointCommentOperateListData.setComment_content(viewpointCommentOperateListView.getComment_content());
            viewpointCommentOperateListData.setCustomer_id(viewpointCommentOperateListView.getCustomer_id());
            viewpointCommentOperateListData.setCustomer_name(viewpointCommentOperateListView.getCustomer_name());
            viewpointCommentOperateListData.setPosition_str(viewpointCommentOperateListView.getPosition_str());
            viewpointCommentOperateListData.setTenant_id(viewpointCommentOperateListView.getTenant_id());
            String commentContent = viewpointCommentOperateListView.getComment_content();
            if (!StringUtil.isBlank(commentContent)) {
                JSONArray jsonArray = JSON.parseArray(commentContent);
                for (int i = 0; i < jsonArray.size(); i++){
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    if (jsonObject.get("type").equals("text")) {
                        if (!StringUtil.isBlank(jsonObject.getString("body"))) {
                            viewpointCommentOperateListData.setComment_text_content(jsonObject.getString("body"));
                            break;
                        }
                    }
                }
            }
            if (StringUtil.isBlank(viewpointCommentOperateListData.getComment_text_content())) {
                viewpointCommentOperateListData.setComment_text_content("该评论无文本内容");
            }
            resultList.add(viewpointCommentOperateListData);
        }
        result.setPage_no(pageNo);
        result.setTotal_item_num(counts);
        result.newDataList().addAll(resultList);
        return VOUtil.setSuccessResult(result);
    }

    @Override
    public HSBCPSBackVO funcViewpointCommentDelete(ViewpointCommentOperateDeleteForm form) {
        String viewpointDeleteId = form.getViewpoint_delete_id();
        JSONObject viewpointDeleteIdObject = JSON.parseObject(viewpointDeleteId);
        JSONArray jsonArray = JSONUtil.toJsonArray(viewpointDeleteIdObject.get("viewpoint_delete_id_list"));
        List<ViewpointReplyId> viewpointReplyIds = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            ViewpointReplyId viewpointReplyId = new ViewpointReplyId();
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            viewpointReplyId.setViewpoint_reply_id(jsonObject.getLong("viewpoint_reply_id"));
            viewpointReplyId.setTenant_id(jsonObject.getInteger("tenant_id"));
            viewpointReplyIds.add(viewpointReplyId);
        }
        if (!viewpointReplyIds.isEmpty()) {
            Integer counts = viewpointReplyService.countByIds(viewpointReplyIds);
            if (!counts.equals(viewpointReplyIds.size())) {
                return VOUtil.genErrorResultVo(HSBCPSErrorCodes.OperateErr.DELETE_ID_ERR);
            }
            ViewpointReply viewpointReply = viewpointReplyService.getById(viewpointReplyIds.get(0).getViewpoint_reply_id(), viewpointReplyIds.get(0).getTenant_id());
            ViewpointMsg msg = this.viewpointMsgService.getByTenantId(viewpointReply.getViewpoint_id(), viewpointReplyIds.get(0).getTenant_id());
            if (null != msg) {
                viewpointReplyService.deleteByIds(viewpointReplyIds);
                if (msg.getComment_num() < viewpointReplyIds.size()) {
                    return VOUtil.genErrorResultVo(HSBCPSErrorCodes.OperateErr.DELETE_ID_ERR);
                }
                msg.setComment_num(msg.getComment_num() - viewpointReplyIds.size());
                this.viewpointMsgService.update(msg);
            } else {
                return VOUtil.genErrorResultVo(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_VIEWPOINT_COMM_ID);
            }
        }
        return VOUtil.genSuccessBackVo();
    }
    @Override
    public SelfViewpointResult funcSelfViewpointsList(SelfViewpointForm form) {
        SelfViewpointResult result = new SelfViewpointResult();
        String key_word = form.getKey_word();
        Integer page_no = ValueUtil.getInt(form.getPage_no(), 1);
        Integer page_count = ValueUtil.getInt(form.getPage_count(), ConfigValues.getRequestNum());
        String field_sort = "send_time";
        String sort_order = "desc";
        String viewpoint_review_type = "0";
        List<Map<String, Object>> list = SearchUtil.getInstance().getSelfMediaList(key_word, page_no, page_count,
                field_sort, sort_order, viewpoint_review_type);
        List<SelfViewpointList> selfViewpointLists = new ArrayList<>();
        // FIXME: 2016/12/28 确保这里branch_no是只有一个的，而不是逗号隔开
        String public_review_flag = tenantService.getSelfFlagByBranchNo(form.getBranch_no());
        if (StringUtil.isEmpty(public_review_flag) || public_review_flag == "nil") {
            public_review_flag = "0";
        }
        if (list != null && list.size() > 0) {
            for (Map<String, Object> map : list) {
                SelfViewpointList selfViewpointList = new SelfViewpointList();
                selfViewpointList.setBroker_name(ValueUtil.getString(map.get("broker_name")));
                selfViewpointList.setViewpoint_abstract(ValueUtil.getString(map.get("label")));
                selfViewpointList.setSelf_viewpoint_id(ValueUtil.getLong(map.get("id")));
                String content = ValueUtil.getString(map.get("content"));
                selfViewpointList.setContent(ViewpointMsgFormatUtil.parseContext(content));
                String time = ValueUtil.getString(map.get("send_time"));
                if (!ValueUtil.isEmpty(time)) {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(time.substring(0, 4)).append("-").append(time.substring(4, 6)).append("-")
                            .append(time.substring(6, 8)).append(" ").append(time.substring(8, 10)).append(":")
                            .append(time.substring(10, 12)).append(":").append(time.substring(12, 14));
                    time = stringBuilder.toString();
                }
                selfViewpointList.setSend_time(time);
                selfViewpointList.setTitle(ValueUtil.getString(map.get("viewpoint_title")));
                String public_review_status = ValueUtil.getString(map.get("public_review_status"));
                selfViewpointList.setPublic_review_status(public_review_status);
                Map<String, Object> totalmap = list.get(0);
                result.setTotal_item_num(ValueUtil.getInt(totalmap.get("total")));
                selfViewpointLists.add(selfViewpointList);
            }
            result.setData_list(selfViewpointLists);
            result.setPublic_review_flag(public_review_flag);
            result.setPage_no(page_no);
            return VOUtil.setSuccessResult(result);
        } else {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_HISTORY_RECORD,
                    SelfViewpointResult.class);
        }
    }

    @Override
    public HSBCPSBackVO funcSelfViewpointReview(SelfViewpointReviewForm form) {
        String public_review_flag = form.getPublic_review_flag();
        List<Long> tenantIds = tenantService.getTenantIdsByBranchNo(form.getBranch_no());
        if (tenantIds == null || tenantIds.isEmpty()){
            return VOUtil.genErrorResultVo(HSBCPSErrorCodes.OperateErr.TENANT_NOT_EXIST_BY_BRANCH);
        }
        tenantService.updateSelfFlagByTenantIds(tenantIds, public_review_flag);
        HSBCPSBackVO result = new HSBCPSBackVO();
        return VOUtil.setSuccessResult(result);
    }

    @Override
    public HSBCPSBackVO funcSelfViewpointReviewStatus(SelfViewpointStatusForm form) {
        SearchUtil.getInstance().updateSearchById(form.getSelf_viewpoint_id(), form.getPublic_review_status());
        viewpointMsgService.funcViewpointReviewByIdManage(form.getSelf_viewpoint_id(),form.getPublic_review_status());
        HSBCPSBackVO result = new HSBCPSBackVO();
        return VOUtil.setSuccessResult(result);
    }

    @Override
    public SelfViewpointBack funcSelfViewpointById(SelfViewpointByIdForm form) {
        String selfViewpoinId = form.getSelf_viewpoint_id();
        Map<String, Object> map = SearchUtil.getInstance().getSelfViewpointById(selfViewpoinId);
        if (ValueUtil.isEmpty(map)) {
            return VOUtil
                    .genErrorResult(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_HISTORY_RECORD, SelfViewpointBack.class);
        }
        SelfViewpointBack result = new SelfViewpointBack();
        result.setBroker_name(ValueUtil.getString(map.get("broker_name")));
        result.setViewpoint_abstract(ValueUtil.getString(map.get("label")));
        result.setSelf_viewpoint_id(ValueUtil.getLong(map.get("id")));
        String content = ValueUtil.getString(map.get("content"));
        result.setContent(ValueUtil.getString(ViewpointMsgFormatUtil.parseContext(content)));
        String time = ValueUtil.getString(map.get("send_time"));
        if (!ValueUtil.isEmpty(time)) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(time.substring(0, 4)).append("-").append(time.substring(4, 6)).append("-")
                    .append(time.substring(6, 8)).append(" ").append(time.substring(8, 10)).append(":")
                    .append(time.substring(10, 12)).append(":").append(time.substring(12, 14));
            time = stringBuilder.toString();
        }
        result.setSend_time(time);
        result.setTitle(ValueUtil.getString(map.get("viewpoint_title")));
        return VOUtil.setSuccessResult(result);
    }
    

    @Override
    public ViewpointDetailDavList funcBrokerViewpointDetailList(ViewpointDetailListForm param) {
        Long userId = ValueUtil.getLong(param.getUser_id());
        ViewpointDetailDavList ret = new ViewpointDetailDavList();
        BrokerManager brokerManager = brokerManagerService.getByUserId(userId);
        if (null == brokerManager) {
            return VOUtil.setSuccessResult(ret);
        }
        Long brokerId = brokerManager.getBroker_id();
        Integer tenant_id = brokerManager.getTenant_id();
        int page_no = Integer.parseInt(param.getPage_no());
        int page_count = Integer.parseInt(param.getPage_count());
        Integer total_count = viewpointMsgService.countByBrokerId(brokerId, tenant_id);
        List<ViewpointDetailDavView> msgs = this.viewpointMsgService.queryViewpointDetailDavList(brokerId,
                (page_no - 1) * page_count, page_count);
        ret.newDataList().addAll(msgs);
        ret.setTotal_count(total_count);
        return VOUtil.setSuccessResult(ret);
    }
}
